home *** CD-ROM | disk | FTP | other *** search
/ Night Owl 6 / Night Owl's Shareware - PDSI-006 - Night Owl Corp (1990).iso / 016a / gofer221.zip / CH14 < prev    next >
Text File  |  1991-11-20  |  79KB  |  2,113 lines

  1.  
  2.  
  3. Introduction to Gofer         14. OVERLOADING IN GOFER                          
  4.  
  5.  
  6. 14. OVERLOADING IN GOFER
  7.  
  8. One of the biggest differences between Gofer and most other programming
  9. languages  (with  the  exception  of  Haskell)  is  the   approach   to
  10. overloading; enabling the definition and use of functions in which  the
  11. meaning of a function symbol may depend on the types of its arguments.
  12.  
  13. Like Haskell, overloading in Gofer is based around  a  system  of  type
  14. classes which allow overloaded functions to be  grouped  together  into
  15. related groups  of  functions.   Whilst  the  precise  details  of  the
  16. approach to type classes used by Gofer are quite different to those  of
  17. Haskell, both rely on the same basic ideas and use a similar syntax for
  18. defining and using type classes.  It would therefore seem possible that
  19. experience gained with the  overloading  system  in  one  language  can
  20. readily by applied to the other.
  21.  
  22. The differences embodied in the Gofer system of classes  stem  from  my
  23. own, theoretically based investigations into `qualified types' some  of
  24. which is detailed in references [8-12].  In my  personal  opinion,  the
  25. Gofer system has some significant advantages over the Haskell  approach
  26. (see [12] for details) and one of the principal motivations behind  the
  27. implementation to Gofer was to provide a way of  testing  such  claims.
  28. One fact which I believe has already been established  using  Gofer  is
  29. that the use and implementation of overloaded functions need  not  have
  30. the significant effect on performance that was anticipated  with  early
  31. implementations of Haskell.
  32.  
  33. This section outlines  the  system  of  type  classes  used  in  Gofer,
  34. indicating briefly how they can be used and how they are implemented.
  35.  
  36.  
  37. 14.1 Type classes and predicates
  38. --------------------------------
  39. A type class can be thought of as a family of types (or more  generally
  40. as a family of tuples of types) whose elements are called instances  of
  41. the class.  If C is the name of  an  n-parameter  type  class  then  an
  42. expression of the form C t1 t2 ... tn where t1, t2, ...,  tn  are  type
  43. expressions is called a predicate and represents the assertion that the
  44. specified tuple of types is an instance of the class C.
  45.  
  46. Given a polymorphic function (e.g. map::(a->b)->[a]->[b]), we are  free
  47. to use the function at any type which can be obtained  by  substituting
  48. arbitrary types for each of the type variables in its type.  In  Gofer,
  49. a type expression may be qualified by  one  or  more  predicates  which
  50. restrict the range of types at which a value can be used:
  51.  
  52. e.g. a function of type C a => a -> a -> a can be treated as a function
  53.      of type t -> t -> t for any instance t of the class C.
  54.  
  55. The predicate C a in the type expression in  the  previous  example  is
  56. called the context of the type.  Contexts may  contain  more  than  one
  57. predicate in which case the predicates involved must  be  separated  by
  58. commas and the context enclosed in parentheses as in (C a, D  b).   The
  59. empty context is written () and any type expression t is equivalent  to
  60. the qualified type () => t.  For uniformity, a context  with  only  one
  61. element may also be enclosed by parentheses.
  62.  
  63.  
  64.                                       61
  65.  
  66.  
  67.  
  68.  
  69. Introduction to Gofer         14.1 Type classes and predicates                  
  70.  
  71.  
  72. For technical reasons, type synonyms are  not  currently  permitted  in
  73. predicates.  This is consistent with the use of predicates in  Haskell,
  74. but may be relaxed, at least in certain cases,  in  later  versions  of
  75. Gofer.
  76.  
  77.  
  78. 14.2 The type class Eq
  79. ----------------------
  80. The type class Eq is a simple and useful example, whose  instances  are
  81. precisely those types whose elements can be tested for  equality.   The
  82. declaration of this class given in the standard prelude is as follows:
  83.  
  84.     class Eq a where
  85.         (==), (/=) :: a -> a -> Bool
  86.         x /= y      = not (x == y)
  87.  
  88. There are three parts in any class declaration.   For  this  particular
  89. example we have:
  90.  
  91.   o  The first line (called the `header') of the declaration introduces
  92.      a name Eq for the  class  and  indicates  that  it  has  a  single
  93.      parameter, represented by the type variable a.
  94.  
  95.   o  The  second  line  of  the  declaration  (the  `signature   part')
  96.      indicates that there are functions denoted by the operator symbols
  97.      (==) and (/=) of type a -> a -> Bool for each instance a of  class
  98.      Eq.  Using the notation introduced in the previous  section,  both
  99.      of these operators have type:
  100.  
  101.                       Eq a => a -> a -> Bool
  102.  
  103.      These functions are called the `members' (or  `member  functions')
  104.      of the class.  [This terminology, taken from  Haskell,  is  rather
  105.      unfortunate; thinking of a type class  as  a  set  of  types,  the
  106.      elements of the class are called `instances', whilst the `members'
  107.      of the class correspond more closely  to  the  instance  variables
  108.      that are used in the terminology of object-oriented programming.]
  109.  
  110.      The intention is that the (==) function will be used to  implement
  111.      an equality test for each instance of the  class,  with  the  (/=)
  112.      operator providing the  corresponding  inequality  function.   The
  113.      ability to include related groups of  functions  within  a  single
  114.      type class in this way is a useful tool in program design.
  115.  
  116.   o  The  third  line  of   the   class   declaration   (the   `default
  117.      definitions') provides a default definition of the  (/=)  operator
  118.      in terms of the (==) operator.  Thus it is only necessary to  give
  119.      a definition for the (==) operator in order to define all  of  the
  120.      member functions for the class Eq.  It  is  possible  to  override
  121.      default member definitions by giving an alternative definition  as
  122.      appropriate for specific instances of the class.
  123.  
  124.  
  125.  
  126.  
  127.  
  128.  
  129.  
  130.                                       62
  131.  
  132.  
  133.  
  134.  
  135. Introduction to Gofer         14.2.1 Implicit overloading                       
  136.  
  137.  
  138. 14.2.1 Implicit overloading
  139. ---------------------------
  140. Member functions are clearly marked as overloaded  functions  by  their
  141. definition as part of a class declaration, but this is not the only way
  142. in which overloaded  functions  occur  in  Gofer;  the  restriction  to
  143. particular instances of a type class is also carried over into the type
  144. of any function defined either directly or indirectly in terms  of  the
  145. member functions of that class.  For example, the  types  inferred  for
  146. the following two functions:
  147.  
  148.     x  `elem`   xs   =   any (x==) xs
  149.     xs `subset` ys   =   all (`elem` ys) xs
  150.  
  151. are:
  152.  
  153.     elem   :: Eq a => a -> [a] -> Bool
  154.     subset :: Eq a => [a] -> [a] -> Bool
  155.  
  156. [ASIDE: On the  other  hand,  if  none  of  the  functions  used  in  a
  157. particular expression or definition are overloaded then there will  not
  158. be any overloading in the corresponding value.  Gofer does not  support
  159. the concept of implicit overloading used  in  some  languages  where  a
  160. value of a particular type might automatically be coerced to a value of
  161. some supertype.  An example of this would be the automatic  translation
  162. of a badly typed expression "1.0 == 1" to a  well-typed  expression  of
  163. the form "1.0 == float 1" for some  (potentially  overloaded)  coercion
  164. function "float" mapping numeric values to elements of type Float.]
  165.  
  166. Note also that the types appearing in the context of a  qualified  type
  167. reflect the types at which overloaded functions are used.  Thus:
  168.  
  169.     f x ys  =  [x] == ys
  170.  
  171. has type  Eq [a] => a -> [a] -> Bool, and not Eq a => a -> [a] -> Bool,
  172. which is the type that would be assigned to "f" in a Haskell system.
  173.  
  174.  
  175. 14.2.2 Instances of class Eq
  176. ----------------------------
  177. Instances of a type class are defined  using  declarations  similar  to
  178. those used to define  the  corresponding  type  class.   The  following
  179. examples, taken from the standard prelude, give the definitions  for  a
  180. number of simple instances of the class Eq:
  181.  
  182.     instance Eq Int  where  (==) = primEqInt
  183.  
  184.     instance Eq Bool where
  185.         True  == True   =  True
  186.         False == False  =  True
  187.         _     == _      =  False
  188.  
  189.     instance Eq Char  where  c == d  =  ord c == ord d
  190.  
  191.     instance (Eq a, Eq b) => Eq (a,b) where
  192.         (x,y) == (u,v)  =  x==u && y==v
  193.  
  194.  
  195.  
  196.                                       63
  197.  
  198.  
  199.  
  200.  
  201. Introduction to Gofer         14.2.2 Instances of class Eq                      
  202.  
  203.  
  204.     instance Eq a => Eq [a] where
  205.         []     == []     =  True
  206.         []     == (y:ys) =  False
  207.         (x:xs) == []     =  False
  208.         (x:xs) == (y:ys) =  x==y && xs==ys
  209.  
  210. The interpretation of these declarations is as follows:
  211.  
  212.   o  The first declaration  makes Int an instance  of  class  Eq.   The
  213.      function "primEqInt" is a primitive Gofer function which tests the
  214.      equality of two integer values and has type Int  ->  Int  ->  Bool
  215.      which tests the equality of two integer values.
  216.  
  217.   o  The second declaration makes  Bool an instance of  class Eq with a
  218.      simple definition involving pattern matching.
  219.  
  220.   o  The third declaration makes Char an instance of  class  Eq.   This
  221.      definition indicates that a pair of characters are equal  if  they
  222.      have the same ASCII value,  which  is  obtained  using  the  "ord"
  223.      function.  Note that the two occurrences of the symbol (==) in the
  224.      equation:
  225.  
  226.                        c == d  =  ord c == ord d
  227.  
  228.      have  different  meanings;  the  first  denotes  equality  between
  229.      characters (elements of type  Char),  whilst  the  second  denotes
  230.      equality between integers (elements of type Int).
  231.  
  232.   o  The fourth declaration provides an equality  operation  on  pairs.
  233.      Given two elements (x,y) and (u,v) of type (a,b) for some a, b, it
  234.      must be possible to check that both x==u and y==v before we can be
  235.      sure that the two pairs are indeed equal.  In other words, both  a
  236.      and b must also be instances of Eq  in  order  to  make  (a,b)  an
  237.      instance of Eq.  This requirement is described by the  first  line
  238.      in the instance declaration using the expression:
  239.  
  240.                        (Eq a, Eq b) => Eq (a,b)
  241.  
  242.   o  The fifth declaration makes [a] an instance of Eq, whenever  a  is
  243.      itself an instance  of  Eq  in  a  similar  way  to  the  previous
  244.      example.  The context Eq a is used in the  last  equation  in  the
  245.      declaration:
  246.  
  247.                      (x:xs) == (y:ys)  =  x==y && xs==ys
  248.  
  249.      which contains three occurrences of the (==) operator;  the  first
  250.      and third are used to compare lists of type [a], whilst the second
  251.      is used to compare elements of type a, using the instance Eq a.
  252.  
  253. Combining these five declarations, we obtain definitions for (==) on an
  254. infinite  family  of  types  including  Int,  Char,  Bool,  (Int,Bool),
  255. (Char,Int), [Char], (Bool,[Int]), [(Bool,Int)], etc...:
  256.  
  257.     ? 2 == 3                            -- using Eq Int
  258.     False
  259.     (2 reductions, 10 cells)
  260.  
  261.  
  262.                                       64
  263.  
  264.  
  265.  
  266.  
  267. Introduction to Gofer         14.2.2 Instances of class Eq                      
  268.  
  269.  
  270.     ? (["Hello"],3) == (["Hello"],3)    -- using Eq ([[Char]],Int)
  271.     True
  272.     (31 reductions, 65 cells)
  273.     ?
  274.  
  275. On the other hand, any attempt to use (==) to compare elements of  some
  276. type not covered by a suitable instance declaration will result  in  an
  277. error.  For example, the standard prelude does not define the  equality
  278. operation on triples of values:
  279.  
  280.     ? (1,2,3) == (1,2,3)
  281.     ERROR: Cannot derive instance in expression
  282.     *** Expression        : (==) d125 (1,2,3) (1,2,3)
  283.     *** Required instance : Eq (Int,Int,Int)
  284.     ?
  285.  
  286. This can be solved by including an instance  declaration  of  the  form
  287. into a file of definitions loaded into Gofer:
  288.  
  289.     instance (Eq a, Eq b, Eq c) => Eq (a,b,c) where
  290.         (x,y,z) == (u,v,w)  =  x==u && y==v && z==w
  291.  
  292. Giving:
  293.  
  294.     ? (1,2,3) == (1,2,3)
  295.     True
  296.     (6 reductions, 20 cells)
  297.     ?
  298.  
  299. In general, an instance declaration has the form:
  300.  
  301.              instance  context => predicate  where
  302.                  definitions of member functions
  303.  
  304. The context part of the declaration gives a list  of  predicates  which
  305. must be satisfied for the predicate on the right hand side of the  `=>'
  306. sign to be valid.  Constant predicates (i.e. predicates  not  involving
  307. any type variables) required by an instance declaration  (such  as  the
  308. predicate Eq Int  required  by  the  third  declaration)  need  not  be
  309. included in the context.  If the resulting context is empty (as in  the
  310. first three declarations above) then it may be omitted,  together  with
  311. the corresponding `=>' symbol.
  312.  
  313.  
  314. 14.2.3 Testing equality of represented values
  315. ---------------------------------------------
  316. Instances of  Eq  can  also  be  defined  for  other  types,  including
  317. user-defined datatypes, and unlike the instances described  above,  the
  318. definition of (==) need not be used to  determine  whether  the  values
  319. being compared have the same structure; it  is  often  more  useful  to
  320. check that they represent the same value.  As an example, suppose  that
  321. we introduce a type constructor Set for representing  sets  of  values,
  322. using a list to store the values held in the set:
  323.  
  324.     data Set a = Set [a]
  325.  
  326.  
  327.  
  328.                                       65
  329.  
  330.  
  331.  
  332.  
  333. Introduction to Gofer         14.2.3 Testing equality of represented values     
  334.  
  335.  
  336. As usual, we say that two sets are equal if they have the same members,
  337. ignoring any repetitions or differences in the ordering of the elements
  338. in the lists  representing  the  sets.   This  is  achieved  using  the
  339. following instance declaration:
  340.  
  341.     instance Eq a => Eq (Set a) where
  342.         Set xs == Set ys  =  xs `subset` ys  &&  ys `subset` xs
  343.                              where xs `subset` ys = all (`elem` ys) xs
  344.  
  345. A couple of examples illustrate the use of this definition:
  346.  
  347.     ? Set [1,2,3] == Set [3,4,1]
  348.     False
  349.     (49 reductions, 89 cells)
  350.     ? Set [1,2,3] == Set [1,2,2,2,1,3]
  351.     True
  352.     (157 reductions, 240 cells)
  353.     ? 
  354.  
  355.  
  356. 14.2.4 Instance declarations without members
  357. --------------------------------------------
  358. It is possible to give an instance declaration without  specifying  any
  359. definitions for the member functions of the class.  For example:
  360.  
  361.     instance Eq ()
  362.  
  363. In this case, the definition of  (==) for the instance  Eq ()  is  left
  364. completely undefined, and hence so is the definition of (/=), which  is
  365. defined in terms of (==):
  366.  
  367.     ? () == ()
  368.     {undefined_member (==)}
  369.     (3 reductions, 34 cells)
  370.     ? () /= ()
  371.     {undefined_member (==)}
  372.     (4 reductions, 36 cells)
  373.     ? 
  374.  
  375.  
  376. 14.2.5 Equality on function types
  377. ---------------------------------
  378. If an expression requires an  instance  of  a  class  which  cannot  be
  379. obtained using the rules in the given instance  declarations,  then  an
  380. error message will be produced when  the  expression  is  type-checked.
  381. For example, in general there is no sensible way to  determine  when  a
  382. pair of functions are equal, and the standard prelude does not  include
  383. a definition for an instance of the form Eq (a -> b) for  any  types  a
  384. and b:
  385.  
  386.     ? (1==) == (\x->1==x)
  387.     ERROR: Cannot derive instance in expression
  388.     *** Expression        : (==) d148 ((==) {dict} 1) (\x->(==) {dict} 1 x)
  389.     *** Required instance : Eq (Int -> Bool)
  390.  
  391.     ?
  392.  
  393.  
  394.                                       66
  395.  
  396.  
  397.  
  398.  
  399. Introduction to Gofer         14.2.5 Equality on function types                 
  400.  
  401.  
  402. If for some reason, you would prefer this kind of error to  produce  an
  403. error message when an expression is evaluated, rather than when  it  is
  404. type-checked, you can  use  an  instance  declaration  to  specify  the
  405. required behaviour.  For example:
  406.  
  407.     instance Eq (a -> b) where 
  408.         (==) = error "Equality not defined between functions"
  409.  
  410. Evaluating the previous expression once this instance  declaration  has
  411. been included now produces the following result:
  412.  
  413.     ? (1==) == (\x->1==x)
  414.     {error "Equality not defined between functions"}
  415.     (42 reductions, 173 cells)
  416.     ? 
  417.  
  418. A limited form of equality can be defined for functions of type  (a->b)
  419. if a has only finitely many elements, such as the boolean type Bool:
  420.  
  421.     instance Eq a => Eq (Bool -> a) where
  422.         f == g   =   f False == g False   &&   f True == g True
  423.  
  424. [ASIDE: This instance declaration would not be accepted  in  a  Haskell
  425. program which insists that the predicate  on  the  right  of  the  `=>'
  426. symbol contains precisely one type constructor symbol.]
  427.  
  428. Using this instance declaration once for each argument, we can now test
  429. two functions taking boolean arguments for equality (assuming of course
  430. that their result type is also an instance of Eq).
  431.  
  432.     ? (&&) == (||)
  433.     False
  434.     (9 reductions, 21 cells)
  435.     ? not == (\x -> if x then False else True)
  436.     True
  437.     (8 reductions, 16 cells)
  438.     ? (&&) == (\x y-> if x then y else False)
  439.     True
  440.     (16 reductions, 30 cells)
  441.     ? 
  442.  
  443.  
  444. 14.2.6 Non-overlapping instances
  445. --------------------------------
  446. Other instance declarations for types of the form a -> b can be used at
  447. the same time, so  long  as  no  pair  of  declarations  overlap.   For
  448. example, adding the following instance declaration
  449.  
  450.     instance Eq a => Eq (() -> a)  where  f == g  =  f () == g ()
  451.  
  452. enables us to evaluate expressions such as:
  453.  
  454.     ? (\()->"Hello") == const "Hello"
  455.     True
  456.     (30 reductions, 55 cells)
  457.     ? 
  458.  
  459.  
  460.                                       67
  461.  
  462.  
  463.  
  464.  
  465. Introduction to Gofer         14.2.6 Non-overlapping instances                  
  466.  
  467.  
  468. If however, we try and use instance declarations for types of the  form
  469. (a -> b) and (Bool -> a) at the same time, then Gofer produces an error
  470. message similar to the following:
  471.  
  472.     ERROR "file" (line 37): Overlapping instances for class "Eq"
  473.     *** This instance   : Eq (a -> b)
  474.     *** Overlaps with   : Eq (Bool -> a)
  475.     *** Common instance : Eq (Bool -> a)
  476.  
  477.     ? 
  478.  
  479. indicating that, given the task of testing two values of type (Bool->a)
  480. for equality, there are (at least) two definitions of (==)  that  could
  481. be used, with potentially different  results  being  obtained  in  each
  482. case.
  483.  
  484. Here is a further example of the use of non-overlapping instances of  a
  485. class to define a function "cat" (inspired by the unix (tm) command  of
  486. the same name) which uses the I/O facilities  of  Gofer  to  print  the
  487. contents of one or more files on the terminal:
  488.  
  489.     class    Cat a        where cat  :: a -> Dialogue
  490.     instance Cat [Char]   where cat n = showFile n done
  491.     instance Cat [[Char]] where cat   = foldr showFile done
  492.  
  493.     showFile name cont = readFile name abort
  494.                              (\s->appendChan stdout s abort cont)
  495.  
  496. Given these declarations, an expression of the form:
  497.  
  498.                             cat "file"
  499.  
  500. can be used to display the contents of the named file, whilst a list of
  501. files can be printed one after the other using  an  expression  of  the
  502. form:
  503.  
  504.                cat ["file1", "file2", ..., "filen"].
  505.  
  506.  
  507. 14.3 Dictionaries
  508. -----------------
  509. In order to understand some of the messages produced by Gofer, as  well
  510. as  some  of  the  more  subtle  problems  associated  with  overloaded
  511. functions, it is useful to have a  rough  idea  of  the  way  in  which
  512. overloaded functions are implemented.
  513.  
  514. The basic idea is that a function with a qualified type context => type
  515. where context is a non-empty list of predicates  is  implemented  by  a
  516. function which takes an  extra  argument  for  each  predicate  in  the
  517. context.  When the function is used, each of these parameters is filled
  518. by a `dictionary'  which  gives  the  values  of  each  of  the  member
  519. functions in the appropriate class.  None of these extra parameters  is
  520. entered by the programmer.  Instead, they  are  inserted  automatically
  521. during type-checking.
  522.  
  523. For the class Eq, each dictionary has at least two elements  containing
  524.  
  525.  
  526.                                       68
  527.  
  528.  
  529.  
  530.  
  531. Introduction to Gofer         14.3 Dictionaries                                 
  532.  
  533.  
  534. definitions for each of the functions (==) and (/=).  A dictionary  for
  535. an instance of Eq can be depicted by a diagram of the form:
  536.  
  537.                      +--------+--------+---------
  538.                      |        |        |
  539.                      |  (==)  |  (/=)  |  .....
  540.                      |        |        |
  541.                      +--------+--------+---------
  542.  
  543. In order to produce useful error messages and indicate the way in which
  544. dictionary expressions are being used, Gofer uses a number  of  special
  545. notations for printing expressions involving dictionaries:
  546.  
  547.    (#1 d)   selects the first element of the dictionary d
  548.  
  549.    (#2 d)   selects the second element of the dictionary d
  550.  
  551.    (#n d)   selects the nth element of the dictionary d
  552.             (note that (#0 d) is equivalent to the dictionary d).
  553.  
  554.    {dict}   denotes a specific dictionary (the contents are not
  555.             displayed).
  556.  
  557.    dnnn     a dictionary variable representing an unknown dictionary is
  558.             printed as a lower case letter `d' followed by an  integer;
  559.             e.g. d231.
  560.  
  561. Note that, whilst these notations are used in output produced by  Gofer
  562. and in the following explanations, they cannot be entered directly into
  563. Gofer expressions or programs -- even if you use  a  variable  such  as
  564. "d1" in an expression, Gofer will not confuse this  with  a  dictionary
  565. variable with the same name (although Gofer might confuse you by  using
  566. the same name in two different contexts!).
  567.  
  568. Using these notations, the member functions (==) and (/=) of the  class
  569. Eq behave as if they were defined by the expressions:
  570.  
  571.     (==) d1  =  (#1 d1)
  572.     (/=) d1  =  (#2 d1)
  573.  
  574. To understand how these definitions work, we need to take a look  at  a
  575. specific dictionary.  Following the original instance declaration  used
  576. for Eq Int, the corresponding dictionary is:
  577.  
  578.                     d :: Eq Int
  579.                     +------------+------------+
  580.                     |            |            |
  581.                     | primEqInt  |  defNeq d  |
  582.                     |            |            |
  583.                     +------------+------------+
  584.  
  585. Note that the  dictionary  variable  d  is  used  as  a  name  for  the
  586. dictionary in this diagram, indicating how values within  a  dictionary
  587. can include references to the same dictionary.
  588.  
  589. [ASIDE: It turns out that predicates  play  a  very  similar  role  for
  590.  
  591.  
  592.                                       69
  593.  
  594.  
  595.  
  596.  
  597. Introduction to Gofer         14.3 Dictionaries                                 
  598.  
  599.  
  600. dictionaries as types play for normal values.  This motivates  our  use
  601. of the notation d :: Eq Int to indicate that d is a dictionary for  the
  602. instance Eq Int.  One difference between these, particularly  important
  603. for theoretical work, is that dictionary values are uniquely determined
  604. by predicates; if d1::p and d2::p for some predicate p, then d1 = d2.]
  605.  
  606. The value held in the first element of the dictionary is the  primitive
  607. equality function on  integers,  "primEqInt".   The  following  diagram
  608. shows how the dictionary is used to evaluate the expression "2  ==  3".
  609. Note that this expression will first be translated to  "(==) d 2 3"  by
  610. the type checker.  The evaluation then proceeds as follows:
  611.  
  612.     (==) d 2 3  ==>  (#1 d) 2 3
  613.                 ==>  primEqInt 2 3
  614.                 ==>  False
  615.  
  616. The second element of the  dictionary  is  a  little  more  interesting
  617. because it uses the default definition for (/=) given in  the  original
  618. class definition  which,  after  translation,  is  represented  by  the
  619. function "defNeq" defined by:
  620.  
  621.     defNeq d1 x y = not ((==) d1 x y)
  622.  
  623. Notice the way in which the  extra  dictionary  parameter  is  used  to
  624. obtain the appropriate overloading.  For  example,  evaluation  of  the
  625. expression  "2 /= 3", which  becomes  "(/=) d 2 3"  after  translation,
  626. proceeds as follows:
  627.  
  628.     (/=) d 2 3  ==>  (#2 d) 2 3
  629.                 ==>  defNeq d 2 3
  630.                 ==>  not ((==) d 2 3)
  631.                 ==>  not ((#1 d) 2 3)
  632.                 ==>  not (primEqInt 2 3)
  633.                 ==>  not False
  634.                 ==>  True
  635.  
  636. [Clearly there is some scope for optimisation here; whilst  the  actual
  637. reduction sequences used by Gofer are equivalent to  those  illustrated
  638. above, the precise details are a little different.]
  639.  
  640. If an  instance  is  obtained  from  an  instance  declaration  with  a
  641. non-empty context, then the basic two element dictionary  used  in  the
  642. examples above is extended with an  extra  dictionary  value  for  each
  643. predicate in the context.  As an example, the diagram below  shows  the
  644. dictionaries that will be created  from  the  instance  definitions  in
  645. section 14.2.2  for  the  instance  Eq  (Int,  [Int]).   The  functions
  646. "eqPair" and "eqList" which are used in these dictionaries are obtained
  647. from the definitions of (==) given in the instance declarations for  Eq
  648. (a,b) and Eq [a] respectively:
  649.  
  650.     eqPair d (x,y) (u,v)   = (==) (#3 d) x u && (==) (#4 d) y v
  651.  
  652.     eqList d [] []         = True
  653.     eqList d []     (y:ys) = False
  654.     eqList d (x:xs) []     = False
  655.     eqList d (x:xs) (y:ys) = (==) (#3 d) x y && (==) d xs ys
  656.  
  657.  
  658.                                       70
  659.  
  660.  
  661.  
  662.  
  663. Introduction to Gofer         14.3 Dictionaries                                 
  664.  
  665.  
  666. The dictionary structure for Eq (Int, [Int]) is as follows.  Note  that
  667. the Gofer system ensures that there is at most  one  dictionary  for  a
  668. particular instance of a class, and that the dictionary d1 :: Eq Int in
  669. this system is automatically shared between d2 and d3:
  670.  
  671.    d3 :: Eq (Int, [Int])
  672.    +------------+------------+------------+------------+
  673.    |            |            |            |            |
  674.    | eqPair d3  | defNeq d3  | d1::Eq Int |d2::Eq [Int]|
  675.    |            |            |            |            |
  676.    +------------+------------+-----+------+-----+------+
  677.                                    |            |
  678.                     +--------------+            |
  679.                     |                           |
  680.                     |        d2 :: Eq [Int]     V 
  681.                     |        +------------+------------+------------+
  682.                     |        |            |            |            |
  683.                     |        | eqList d2  | defNeq d2  | d1::Eq Int |
  684.                     |        |            |            |            |
  685.                     |        +------------+------------+-----+------+
  686.                     |                                        |
  687.        d1 :: Eq Int V                                        |
  688.        +------------+------------+                           |
  689.        |            |            |                           |
  690.        | primEqInt  | defNeq d1  |<--------------------------+
  691.        |            |            |
  692.        +------------+------------+
  693.  
  694. Once again, it may be useful to see how these definitions are  used  to
  695. evaluate  the  expression   "(2,[1])   ==   (2,[1,3])"   which,   after
  696. translation, becomes "(==) d3 (2,[1]) (2,[1,3])":
  697.  
  698.     (==) d3 (2,[1]) (2,[1,3])
  699.              ==>   (#1 d3) (2,[1]) (2,[1,3])
  700.              ==>   eqPair d3 (2,[1]) (2,[1,3])
  701.              ==>   (==) (#3 d3) 2 2  &&  (==) (#4 d3) [1] [1,3]
  702.              ==>   (==) d1 2 2       &&  (==) (#4 d3) [1] [1,3]
  703.              ==>   (#1 d1) 2 2       &&  (==) (#4 d3) [1] [1,3]
  704.              ==>   primEqInt 2 2     &&  (==) (#4 d3) [1] [1,3]
  705.              ==>   True              &&  (==) (#4 d3) [1] [1,3]
  706.              ==>   (==) (#4 d3) [1] [1,3]
  707.              ==>   (==) d2 [1] [1,3]
  708.              ==>   (#1 d2) [1] [1,3]
  709.              ==>   eqList d2 [1] [1,3]
  710.              ==>   (==) (#3 d2) 1 1  &&  (==) d2 [] [3]
  711.              ==>   (==) d1 1 1       &&  (==) d2 [] [3]
  712.              ==>   (#1 d1) 1 1       &&  (==) d2 [] [3]
  713.              ==>   primEqInt 1 1     &&  (==) d2 [] [3]
  714.              ==>   True              &&  (==) d2 [] [3]
  715.              ==>   (==) d2 [] [3]
  716.              ==>   False
  717.  
  718.  
  719.  
  720.  
  721.  
  722.  
  723.  
  724.                                       71
  725.  
  726.  
  727.  
  728.  
  729. Introduction to Gofer         14.3.1 Superclasses                               
  730.  
  731.  
  732. 14.3.1 Superclasses
  733. -------------------
  734. In general, a type class declaration has the form:
  735.  
  736.              class  context => Class a1 ... an  where
  737.                  type declarations for member functions
  738.                  default definitions of member functions
  739.  
  740. where Class is the name of the new type class which takes n  arguments,
  741. represented by distinct type variables a1, ..., an.  As in the case  of
  742. instance declarations, the context that appears on the left  hand  side
  743. of the `=>'  symbol  specifies  a  list  of  predicates  that  must  be
  744. satisfied in order to construct any instance of "Class".
  745.  
  746. The predicates in the context part of a class  declaration  are  called
  747. the superclasses of Class.  This  terminology  is  taken  from  Haskell
  748. where all classes have a single parameter and each of the predicates in
  749. the context part of a class declaration has the  form  C  a1;  in  this
  750. situation, any instance of Class must also be an instance of each class
  751. C named in the context.   In  other  words,  each  such  C  contains  a
  752. superset of the types in Class.
  753.  
  754. As an example of a class declaration with a non-empty context, consider
  755. the following declaration from the standard prelude which introduces  a
  756. class Ord whose instances are types  with  both  strict  (<),  (>)  and
  757. non-strict  (<=),  (>=)  versions  of  an  ordering  defined  on  their
  758. elements:
  759.  
  760.     class Eq a => Ord a where
  761.         (<), (<=), (>), (>=) :: a -> a -> Bool
  762.         max, min             :: a -> a -> a
  763.  
  764.         x <  y            = x <= y && x /= y
  765.         x >= y            = y <= x
  766.         x >  y            = y < x
  767.  
  768.         max x y | x >= y  = x
  769.                 | y >= x  = y
  770.         min x y | x <= y  = x
  771.                 | y <= x  = y
  772.  
  773. Notice that this definition provides default definitions for all of the
  774. member functions except (<=), so  that  in  general  only  this  single
  775. function needs to be defined to construct an instance of class Ord.
  776.  
  777. There are two reasons for defining Eq as a superclass of Ord:
  778.  
  779.   o  The default definition for (<) relies on the  use  of  (/=)  taken
  780.      from class Eq.  In order to guarantee that this is always valid we
  781.      must ensure that every instance of Ord must also be an instance of
  782.      Eq.
  783.  
  784.   o  Given the definition of a non-strict ordering (<=) on the elements
  785.      of a type, it is always possible to construct a definition for the
  786.      (==) operator (and hence for (/=)) using the equation:
  787.  
  788.  
  789.  
  790.                                       72
  791.  
  792.  
  793.  
  794.  
  795. Introduction to Gofer         14.3.1 Superclasses                               
  796.  
  797.  
  798.                       x==y   =   x<=y && y<=x
  799.  
  800.      There will therefore be no loss in generality by requiring  Eq  to
  801.      be a superclass of Ord, and conversely, no difficulty in  defining
  802.      an instance of Eq to accompany any instance of Ord for which an
  803.      instance of Eq has not already be provided.
  804.  
  805.      As an example, the following definitions  provide  an  alternative
  806.      way to implement the equality operation on  elements  of  the  Set
  807.      datatype described in section  14.2.3,  in  terms  of  the  subset
  808.      ordering defined in class Ord:
  809.  
  810.          instance Ord (Set a) => Eq (Set a) where
  811.              x == y   =   x <= y  &&  y <= x
  812.  
  813.          instance Eq a => Ord (Set a) where
  814.              Set xs <= Set ys  =  all (`elem` ys) xs
  815.  
  816.      This definition is in fact no less efficient or effective than the
  817.      original version.
  818.  
  819. Dictionaries for superclasses are dealt with in much the  same  way  as
  820. the instance specific dictionaries described above.  For  example,  the
  821. general layout of a dictionary for an instance of Ord is illustrated in
  822. the following diagram:
  823.  
  824.  +--------+--------+--------+--------+--------+--------+--------+-----
  825.  |        |        |        |        |        |        |        |
  826.  |  (<)   |  (<=)  |  (>)   |  (>=)  |  max   |  min   |  Eq a  | .....
  827.  |        |        |        |        |        |        |        |
  828.  +--------+--------+--------+--------+--------+--------+--------+-----
  829.  
  830. Note the use of the seventh element of this dictionary which points  to
  831. the dictionary for the appropriate instance of Eq.  This is used in the
  832. translation of the default definition for (<) which is equivalent to:
  833.  
  834.       defLessThan d x y  =  (<=) d x y  &&  (/=) (#7 d) x y
  835.  
  836.  
  837. 14.3.2 Combining classes
  838. ------------------------
  839. In general, a dictionary is made up of three separate parts:
  840.  
  841.      +-------------------+-------------------+-------------------+
  842.      |  Implementation   |    Superclass     | Instance specific |
  843.      | of class members  |   Dictionaries    |   Dictionaries    |
  844.      |                   |                   |                   |
  845.      +-------------------+-------------------+-------------------+
  846.  
  847. Each of these may be empty.  We have already  seen  examples  in  which
  848. there are no superclass dictionaries (e.g.  instances  of  Eq)  and  in
  849. which there are no  instance  specific  dictionaries  (e.g.   Eq  Int).
  850. Classes with no member functions (corresponding to dictionaries with no
  851. member functions) are sometimes useful as a convenient abbreviation for
  852. a list of predicates.  For example:
  853.  
  854.  
  855.  
  856.                                       73
  857.  
  858.  
  859.  
  860.  
  861. Introduction to Gofer         14.3.2 Combining classes                          
  862.  
  863.  
  864.     class  C a  where  cee :: a -> a
  865.     class  D a  where  dee :: a -> a
  866.  
  867.     class  (C a, D a) => CandD a
  868.  
  869. makes CandD a an abbreviation for the context (C a, D a).  Thinking  of
  870. single parameter type classes as sets of types, the  type  class  CandD
  871. corresponds to the intersection of classes C and D.
  872.  
  873. Just as the type inferred  for  a  particular  function  definition  or
  874. expression do not involve type synonyms unless explicit type signatures
  875. are used, the Gofer type system will not use a single predicate of  the
  876. form CandD a instead of the two predicates C a and D a unless  explicit
  877. signatures are used:
  878.  
  879.     ? :t dee . cee
  880.     \d129 d130 -> dee d130 . cee d129 :: (C a, D a) => a -> a
  881.     ? :t dee . cee :: CandD a => a -> a
  882.     \d129 -> dee (#2 d129) . cee (#1 d129) :: CandD a => a -> a
  883.     ?
  884.  
  885. In Haskell, all instances of  a  class  such  as  CandD  must  be  have
  886. explicit declarations, in addition to  the  corresponding  declarations
  887. for instances for C and D.  This problem can be avoided  by  using  the
  888. more general form of instance declaration permitted in Gofer; a  single
  889. instance declaration:
  890.  
  891.     instance CandD a
  892.  
  893. is all that is required to ensure that any instance  of  CandD  can  be
  894. obtained, so long as corresponding instances for C and D can be found.
  895.  
  896.  
  897. 14.3.3 Simplified contexts
  898. --------------------------
  899. Consider the function defined by the following equation:
  900.  
  901.     eg1 x   =   [x] == [x]  ||  x == x
  902.  
  903. This definition does not restrict the type of x in any way except that,
  904. if x :: a, then there must be instances Eq [a] and Eq a which are  used
  905. for the two occurrences of the (==) operator in the equation.  We might
  906. therefore expect the type of eg1 to be:
  907.  
  908.     (Eq [a], Eq a) => a -> Bool
  909.  
  910. with translation:
  911.  
  912.     eg1 d1 d2 x  =  (==) d1 [x] [x]  ||  (==) d2 x x
  913.  
  914. However, as can be seen  from  the  case  where  a=Int  illustrated  in
  915. section 14.3, given d1::Eq [a] we can always find a dictionary for Eq a
  916. by taking the third element of d1 i.e. (#3 d1)::Eq a.  Since it is more
  917. efficient to select an element from a  dictionary  than  to  complicate
  918. both type and translation with extra parameters, the type  assigned  to
  919. "eg1" by default is:
  920.  
  921.  
  922.                                       74
  923.  
  924.  
  925.  
  926.  
  927. Introduction to Gofer         14.3.3 Simplified contexts                        
  928.  
  929.  
  930.     Eq [a] => a -> Bool
  931.  
  932. with translation:
  933.  
  934.     eg1 d1 x  =  (==) d1 [x] [x]  || (==) (#3 d1) x x
  935.  
  936. In general, given a set of predicates corresponding  to  the  instances
  937. required by an expression,  Gofer  will  always  attempt  to  find  the
  938. smallest possible subset of these  predicates  such  that  all  of  the
  939. required dictionaries can still  be  obtained,  whilst  minimising  the
  940. number of dictionary parameters that are used.
  941.  
  942. The original type and translation for eg1 given above can  be  produced
  943. by including an explicit type signature  in  the  file  containing  the
  944. definition of eg1:
  945.  
  946.     eg1   ::  (Eq [a], Eq a) => a -> Bool
  947.     eg1 x  =  [x] == [x]  ||  x == x
  948.  
  949. But even with this definition, Gofer will still always try to  minimise
  950. the number of dictionaries used in any particular expression:
  951.  
  952.     ? :t eg1
  953.     \d153 -> eg1 d153 (#3 d153) :: Eq [a] => a -> Bool
  954.     ?
  955.  
  956. As another example, consider the expression "(\x y->  x==x  ||  y==y)".
  957. The type and translation assigned to this term can  be  found  directly
  958. using Gofer:
  959.  
  960.     ? :t (\x y-> x==x || y==y)
  961.     \d121 d122 x y -> (==) d122 x x ||
  962.                       (==) d121 y y
  963.                   :: (Eq b, Eq a) => a -> b -> Bool
  964.     ?
  965.  
  966. Note that the translation has two dictionary parameters d121  and  d122
  967. corresponding to the two predicates Eq a and Eq b respectively.   Since
  968. both of these dictionaries can be obtained from a  dictionary  for  the
  969. predicate Eq (a,b), we can use an explicit type signature to produce  a
  970. translation which needs only one dictionary parameter:
  971.  
  972.     ? :t (\x y-> x==x || y==y) :: Eq (a,b) => a -> b -> Bool
  973.     \d121 x y -> (==) (#3 d121) x x ||
  974.                  (==) (#4 d121) y y
  975.              :: Eq (a,b) => a -> b -> Bool
  976.     ?
  977.  
  978.  
  979.  
  980.  
  981.  
  982.  
  983.  
  984.  
  985.  
  986.  
  987.  
  988.                                       75
  989.  
  990.  
  991.  
  992.  
  993. Introduction to Gofer         14.4 Other issues                                 
  994.  
  995.  
  996. 14.4 Other issues
  997. -----------------
  998.  
  999. 14.4.1 Unresolved overloading
  1000. -----------------------------
  1001. Consider  the  use  of  the  (==)  operator  in  the  following   three
  1002. situations:
  1003.  
  1004.   o  In the expression "2 == 3", it is clear that the appropriate value
  1005.      for the equality operator in this case is primIntEq as defined  by
  1006.      the instance declaration for Eq Int.  The expression can therefore
  1007.      be translated to "primEqInt 2 3".
  1008.  
  1009.   o  In the function definition "f x  =  x==x",  we  cannot  completely
  1010.      determine the appropriate value for (==) because it depends on the
  1011.      type assigned to the variable "x",  which  may  itself  vary  with
  1012.      different uses of the function "f".  It is however possible to add
  1013.      an extra parameter to the definition,  giving "f d x = (==) d x x"
  1014.      and taking the type of "f" to be Eq a => a -> Bool.
  1015.  
  1016.      In this way, the problem of finding the appropriate definition for
  1017.      the (==) operator is deferred until the function is actually used.
  1018.  
  1019.   o  In the expression "[]==[]", the appropriate value for (==) must be
  1020.      obtained from the dictionary for some instance of the form Eq [a],
  1021.      but there is not  sufficient  information  in  the  expression  to
  1022.      determine what the value of the type variable a should be.
  1023.  
  1024.      Looking back to the instance declaration for Eq [a], we find  that
  1025.      the definition of (==) depends on the value of the dictionary  for
  1026.      the instance Eq a.  In this particular case, it is clear that  the
  1027.      expression will always evaluate to True, regardless of  the  value
  1028.      of this dictionary.  Unfortunately, the only way that this can  be
  1029.      detected is by evaluating the expression to see if the calculation
  1030.      can be completed without reference to the  dictionary  value  (see
  1031.      the comments in the aside at the end of this section).
  1032.  
  1033.      Attempting to evaluate this expression  in  Gofer  will  therefore
  1034.      result in an error message indicating that the expression does not
  1035.      contain sufficient information to resolve the use  of  overloading
  1036.      in the expression:
  1037.  
  1038.          ? [] == []
  1039.          ERROR: Unresolved overloading
  1040.          *** type        : Eq [a] => Bool
  1041.          *** translation : \d129 -> (==) d129 [] []
  1042.          ?
  1043.  
  1044.      Note  that  the  expression  has  been  converted  into  a  lambda
  1045.      expression using the dictionary variable  d129  to  represent  the
  1046.      dictionary for the unknown instance Eq [a].
  1047.  
  1048.      One simple way to resolve the overloading in an expression of this
  1049.      kind is to use an explicit type signature.   For  example,  if  we
  1050.      specify that the second empty list is an empty list of type [Int]:
  1051.  
  1052.  
  1053.  
  1054.                                       76
  1055.  
  1056.  
  1057.  
  1058.  
  1059. Introduction to Gofer         14.4.1 Unresolved overloading                     
  1060.  
  1061.  
  1062.          ? [] == ([]::[Int])
  1063.          True
  1064.          (2 reductions, 9 cells)
  1065.          ?
  1066.  
  1067. The same problem occurs in Haskell, where it  is  described  using  the
  1068. idea of an `ambiguous type' -- i.e.  a  type  expression  of  the  form
  1069. context => type where one or more of the type  variables  appearing  in
  1070. the given context do not appear in  the  remaining  part  of  the  type
  1071. expression.
  1072.  
  1073. Further examples of unresolved overloading occur  with  other  classes.
  1074. As an example consider the class Reader defined by:
  1075.  
  1076.     class Reader a where 
  1077.         parse   :: String -> a   
  1078.         unparse :: a -> String
  1079.  
  1080. whose  member  functions  provide  methods  for  obtaining  the  string
  1081. representation of an element of an instance type,  and  for  converting
  1082. such representations  back  into  the  original  values  (The  standard
  1083. Haskell Text class  contains  similar  functions).   Now  consider  the
  1084. expression "parse . unparse" which maps values from  some  instance  of
  1085. Reader to  values  of  another  instance  via  an  intermediate  string
  1086. representation.
  1087.  
  1088.     ? parse . unparse
  1089.     ERROR: Unresolved overloading
  1090.     *** type        : (Reader a, Reader b) => a -> b
  1091.     *** translation : \d129 d130 -> parse d130 . unparse d129
  1092.     ?
  1093.  
  1094. One of the first things that might surprise the reader here is that the
  1095. value produced by "parse . unparse" does not have to  be  of  the  same
  1096. type as the argument; for example, we would not usually expect to  have
  1097. any sensible interpretation for a floating point number  obtained  from
  1098. the string representation of a boolean value!
  1099.  
  1100. This can be fixed by using an explicit type declaration,  although  the
  1101. expression still produces unresolved overloading:
  1102.  
  1103.     ? (parse . unparse) :: Reader a => a -> a
  1104.     ERROR: Unresolved overloading
  1105.     *** type        : Reader a => a -> a
  1106.     *** translation : \d130 -> parse d130 . unparse d130
  1107.     ?
  1108.  
  1109. Notice however that the type of this expression  is  not  ambiguous  so
  1110. that the unresolved overloading in this example can be eliminated  when
  1111. the function is actually used:
  1112.  
  1113.     ? ((parse . unparse) :: Reader a => a -> a) 'a'
  1114.     'a'
  1115.     (4 reductions, 11 cells)
  1116.     ?
  1117.  
  1118.  
  1119.  
  1120.                                       77
  1121.  
  1122.  
  1123.  
  1124.  
  1125. Introduction to Gofer         14.4.1 Unresolved overloading                     
  1126.  
  1127.  
  1128. A more serious problem occurs with the  expression  "unparse  .  parse"
  1129. which maps string values to string values via some  intermediate  type.
  1130. Clearly this will lead to a problem with unresolved overloading:
  1131.  
  1132.     ? unparse . parse
  1133.     ERROR: Unresolved overloading
  1134.     *** type        : Reader a => String -> String
  1135.     *** translation : \d130 -> unparse d130 . parse (#0 d130)
  1136.     ?
  1137.  
  1138. Notice that the type obtained in  this  case  is  ambiguous;  the  type
  1139. variable a which appears in the predicate Reader a does not  appear  in
  1140. the type String -> String.  There are a number  of  ways  of  resolving
  1141. this kind of ambiguity:
  1142.  
  1143.   o  Using an explicitly typed expression: Assuming  for  example  that
  1144.      Char is an instance of Reader, we can write:
  1145.  
  1146.          ? unparse . (parse :: String -> Char)
  1147.          v113 {dict} . v112 {dict}
  1148.          (5 reductions, 42 cells)
  1149.          ?
  1150.  
  1151.      without any ambiguity.  If such type  signatures  are  used  in  a
  1152.      number of places, it  might  be  better  to  define  an  auxiliary
  1153.      function and use that instead:
  1154.  
  1155.          charParse :: String -> Char
  1156.          charParse  = parse
  1157.  
  1158.          ? unparse . charParse
  1159.          v113 {dict} . charParse
  1160.          (4 reductions, 37 cells)
  1161.          ?
  1162.  
  1163.      In such situations, it  is  perhaps  worth  asking  if  overloaded
  1164.      functions are in  fact  the  most  appropriate  solution  for  the
  1165.      problem in hand!
  1166.  
  1167.   o  Using an extra dummy parameter in a  function  definition.   In  a
  1168.      definition such as:
  1169.  
  1170.          f = unparse . parse
  1171.  
  1172.      we can introduce an additional dummy parameter `x'  which  is  not
  1173.      used except to determine the type of the result produced by  parse
  1174.      in f:
  1175.  
  1176.          f x  =  unparse . (parse `asTypeOf` (\""->x))
  1177.  
  1178.      where the standard prelude operator `asTypeOf` defined by:
  1179.  
  1180.          asTypeOf      :: a -> a -> a
  1181.          x `asTypeOf` _ = x
  1182.  
  1183.      is used to ensure that the type of parse in the definition of f is
  1184.  
  1185.  
  1186.                                       78
  1187.  
  1188.  
  1189.  
  1190.  
  1191. Introduction to Gofer         14.4.1 Unresolved overloading                     
  1192.  
  1193.  
  1194.      the same as that of the function (\""->x) -- in other  words,  the
  1195.      type must be String -> a where a is the type of the variable x.
  1196.  
  1197.      The resulting type for f is:
  1198.  
  1199.           f :: Reader a => a -> String -> String
  1200.  
  1201.      Notice how the addition of the dummy parameter has  been  used  to
  1202.      eliminate the ambiguity present in the original type.
  1203.  
  1204.      This kind of `coding trick' is rather messy and is not recommended
  1205.      for anything but the simplest examples.
  1206.  
  1207. [ASIDE: The idea of evaluating an expression with an ambiguous type  to
  1208. see if it does actually need the unspecified  dictionaries  could  have
  1209. been implemented quite rather easily in Gofer using an otherwise unused
  1210. datatype Unresolved and generating instance declarations such as:
  1211.  
  1212.     instance Eq Unresolved where
  1213.         (==) = error "unresolved overloading for (==)"
  1214.         (/=) = error "unresolved overloading for (/=)"
  1215.  
  1216. for each class.  Given a particular expression, we  can  then  use  the
  1217. type Unused in place of any ambiguous type variables in its type.   The
  1218. evaluation of the expression could then be attempted, either completing
  1219. successfully if  the  dictionaries  are  not  required,  but  otherwise
  1220. resulting in a run-time error.
  1221.  
  1222. This approach is not used in Gofer; instead, the programmer is notified
  1223. of any unresolved  polymorphism  when  the  program  is  type  checked,
  1224. avoiding the possibility that a program  might  contain  an  undetected
  1225. ambiguity.]
  1226.  
  1227.  
  1228. 14.4.2 `Recursive' dictionaries
  1229. -------------------------------
  1230. Unlike Haskell, there are no restrictions on the form of the predicates
  1231. that may appear in the context  part  of  a  Gofer  class  or  instance
  1232. declaration.  This has a  number  of  potentially  useful  applications
  1233. because it enables the  Gofer  programs  to  use  mutually  `recursive'
  1234. systems of dictionaries.
  1235.  
  1236. One example of this is the ability  to  implement  a  large  family  of
  1237. related functions using a group of classes instead of having to  use  a
  1238. single class.  The following example illustrates the technique with  an
  1239. alternative definition for the class Eq in  which  the  (==)  and  (/=)
  1240. operators are placed in different classes:
  1241.  
  1242.     class Neq a => Eq a  where  (==) :: a -> a -> Bool
  1243.  
  1244.     class Eq a => Neq a  where  (/=) :: a -> a -> Bool
  1245.                                 x/=y  = not (x == y)
  1246.  
  1247.  
  1248. [ASIDE: These declarations clash with those in the standard prelude and
  1249. hence cannot actually be used in Gofer unless a modified version of the
  1250.  
  1251.  
  1252.                                       79
  1253.  
  1254.  
  1255.  
  1256.  
  1257. Introduction to Gofer         14.4.2 `Recursive' dictionaries                   
  1258.  
  1259.  
  1260. standard prelude is used instead.]
  1261.  
  1262. If we then give instance declarations:
  1263.  
  1264.     instance Eq Int  where (==) = primEqInt
  1265.     instance Neq Int
  1266.  
  1267. and try to evaluate the expression "2==3" then the following system  of
  1268. dictionaries will be generated:
  1269.  
  1270.         d1 :: Eq Int                   d2 :: Neq Int
  1271.         +-----------+-----------+      +-----------+-----------+
  1272.         |           |           |      |           |           |
  1273.     +-->| primEqInt |d2::Neq Int+----->| defNeq d2 |d1::Eq Int +---+
  1274.     |   |           |           |      |           |           |   |
  1275.     |   +-----------+-----------+      +-----------+-----------+   |
  1276.     |                                                              |
  1277.     +------------------------------<-------------------------------+
  1278.  
  1279. where the function "defNeq" is derived from the default definition in the
  1280. class Neq and is equivalent to:
  1281.  
  1282.                defNeq d x y  =  not ((==) (#2 d) x y)
  1283.  
  1284. Incidentally, if the instance declaration for Neq Int  above  had  been
  1285. replaced by:
  1286.  
  1287.     instance Neq a
  1288.  
  1289. Then the effect of these declarations would be similar to the  standard
  1290. definition of the class Eq, except that it would  not  be  possible  to
  1291. override the  default  definition  for  (/=).   In  other  words,  this
  1292. approach would give the same effect as defining  (/=)  as  a  top-level
  1293. function rather than a member function in the class Eq:
  1294.  
  1295.     class Eq a  where  (==) :: a -> a -> Bool
  1296.  
  1297.     (/=)   ::  Eq a => a -> a -> Bool
  1298.     x /= y  =  not (x == y)
  1299.  
  1300. There are other situations in which recursive dictionaries of the  kind
  1301. described above can be  used.   A  further  example  is  given  in  the
  1302. following section.  Unfortunately, the lack of restrictions on the form
  1303. of class and instance declarations can also lead to  problems  in  some
  1304. (mostly pathological) cases.  As an example, consider the class:
  1305.  
  1306.     class Bad [a] => Bad a  where  bad :: a -> a
  1307.  
  1308. Without defining any instances of Bad, it is not possible to  construct
  1309. any dictionaries for instances of Bad:
  1310.  
  1311.     ? bad 2
  1312.     ERROR: Cannot derive instance in expression
  1313.     *** Expression        : bad d126 2
  1314.     *** Required instance : Bad Int
  1315.     ?
  1316.  
  1317.  
  1318.                                       80
  1319.  
  1320.  
  1321.  
  1322.  
  1323. Introduction to Gofer         14.4.2 `Recursive' dictionaries                   
  1324.  
  1325.  
  1326. If however we add the instance declarations:
  1327.  
  1328.     instance Bad Int where bad = id
  1329.     instance Bad [a] where bad = id
  1330.  
  1331. then any attempt to construct  a  dictionary  for  Bad  Int  will  also
  1332. require a dictionary for the superclass Bad  [Int]  and  then  for  the
  1333. superclass of that instance Bad [[Int]] etc...  Since Gofer has only  a
  1334. finite amount of space for  storing  dictionaries,  this  process  will
  1335. eventually terminate when that space has been used up:
  1336.  
  1337.     ? bad 2
  1338.     ERROR: Dictionary storage space exhausted
  1339.     ?
  1340.  
  1341. [ASIDE: depending on the configuration of your  particular  version  of
  1342. Gofer and on the nature of the class and instance declarations that are
  1343. involved, an alternative error message "ERROR: Too many type  variables
  1344. in type checker" may be produced instead of the message shown above.]
  1345.  
  1346. From a practical point of view, this problem is unlikely to  cause  too
  1347. many real difficulties:
  1348.  
  1349.   o  Class declarations involving  predicates  such  as  those  in  the
  1350.      declaration of Bad are unlikely to be used in realistic programs.
  1351.  
  1352.   o  All dictionaries are constructed before evaluation  begins.   This
  1353.      process is guaranteed to terminate  because  each  new  dictionary
  1354.      that is created uses up part of  the  space  used  to  hold  Gofer
  1355.      dictionaries.  The  construction  process  will  either  terminate
  1356.      successfully once complete, or be aborted as soon as  all  of  the
  1357.      dictionary space has been used.
  1358.  
  1359. It remains to see what impact (if any) this has on realistic  programs,
  1360. and if later versions of  Gofer  should  be  modified  to  impose  some
  1361. syntactic restrictions (as in Haskell) or perhaps some form  of  static
  1362. checking of the contexts appearing in class and instance  declarations.
  1363.  
  1364.  
  1365. 14.4.3 Classes with multiple parameters
  1366. ---------------------------------------
  1367. Gofer is the first language to support the use  of  type  classes  with
  1368. multiple parameters.  This again is  an  experimental  feature  of  the
  1369. language, intended to make it possible to explore  the  claims  from  a
  1370. number of researchers about the use of such classes.
  1371.  
  1372. Initial experiments suggest that multiple parameter  type  classes  are
  1373. likely  to  lead  to  large  numbers  of   problems   with   unresolved
  1374. overloading.  Ultimately, this may mean that such classes are  only  of
  1375. practical use in explicitly typed languages, or  alternatively  that  a
  1376. more powerful and general defaulting mechanism (similar to that used in
  1377. Haskell with numeric classes) is required to  support  user  controlled
  1378. overloading resolution.
  1379.  
  1380. The following declaration introduces a class  Iso  whose  elements  are
  1381. pairs of isomorphic types:
  1382.  
  1383.  
  1384.                                       81
  1385.  
  1386.  
  1387.  
  1388.  
  1389. Introduction to Gofer         14.4.3 Classes with multiple parameters           
  1390.  
  1391.  
  1392.     class Iso b a => Iso a b  where  iso :: a -> b
  1393.  
  1394. The single member function "iso"  represents  the  isomorphism  mapping
  1395. elements of type a to corresponding  elements  of  type  b.   Note  the
  1396. `superclass' context in this declaration which formalises the idea that
  1397. if a is isomorphic to b then b is also isomorphic to a.  The class  Iso
  1398. therefore provides  further  examples  of  the  recursive  dictionaries
  1399. described in the previous section.
  1400.  
  1401. The fact that any type is isomorphic to itself can be described by the
  1402. following instance declaration:
  1403.  
  1404.     instance Iso a a where iso x = x
  1405.  
  1406. For example, the dictionary structure created in order to evaluate the
  1407. expression "iso 2 = 3" is:
  1408.  
  1409.                    d :: Iso Int Int
  1410.                    +--------------+--------------+
  1411.                    |              |              |
  1412.                +-->|      id      |d::Iso Int Int+--+
  1413.                |   |              |              |  |
  1414.                |   +--------------+--------------+  |
  1415.                |                                    |
  1416.                +------------------<-----------------+
  1417.  
  1418.     ? iso 2 == 3
  1419.     False
  1420.     (4 reductions, 11 cells)
  1421.     ? 
  1422.  
  1423. Our first taste of the problems to come occurs when we try to  evaluate
  1424. the expression "iso 2 == iso 3":
  1425.  
  1426.     ? iso 2 == iso 3
  1427.     ERROR: Unresolved overloading
  1428.     *** type        : (Eq a, Iso Int a) => Bool
  1429.     *** translation : \d130 d132 -> (==) d130 (iso d132 2) (iso d132 3)
  1430.     ?
  1431.  
  1432. In this case, the "iso" function is used to map the integers 2 and 3 to
  1433. elements of some type a, isomorphic to Int, and the values produced are
  1434. the compared using (==) at the instance  Eq  a;  there  is  no  way  of
  1435. discovering what the value of a should be  without  using  an  explicit
  1436. type signature.
  1437.  
  1438. Further instances can be defined.  The following two  declarations  are
  1439. needed to describe the (approximate) isomorphism between lists of pairs
  1440. and pairs of lists:
  1441.  
  1442.     instance Iso [(a,b)] ([a],[b]) where  
  1443.         iso xs = (map fst xs, map snd xs)
  1444.  
  1445.     instance Iso ([a],[b]) [(a,b)] where
  1446.         iso (xs,ys) = zip xs ys
  1447.  
  1448.  
  1449.  
  1450.                                       82
  1451.  
  1452.  
  1453.  
  1454.  
  1455. Introduction to Gofer         14.4.3 Classes with multiple parameters           
  1456.  
  1457.  
  1458. Unfortunately, even apparently straightforward examples  give  problems
  1459. with  unresolved  overloading,  forcing  the  use  of   explicit   type
  1460. declarations:
  1461.  
  1462.     ? iso [(1,2),(3,4)]
  1463.     ERROR: Unresolved overloading
  1464.     *** type        : Iso [(Int,Int)] a => a
  1465.     *** translation : \d126 -> iso d126 [(1,2),(3,4)]
  1466.  
  1467.     ? (iso [(1,2),(3,4)]) :: ([Int],[Int])
  1468.     ([1, 3],[2, 4])
  1469.     (22 reductions, 64 cells)
  1470.     ?
  1471.  
  1472. A second example of a multiple  parameter  type  class  is  defined  as
  1473. follows:
  1474.  
  1475.     class Ord a => Collects a b where
  1476.         emptyCollection :: b
  1477.         addToCollection :: a -> b -> b
  1478.         listCollection  :: b -> [a]
  1479.  
  1480. The basic intuition is that the predicate Collects a b  indicates  that
  1481. elements of type b can be used to represent collections of elements  of
  1482. type a.  A number of people have suggested using type classes  in  this
  1483. way to provide features similar to the (similarly named, but  otherwise
  1484. different) classes that occur in object-oriented languages.
  1485.  
  1486. Obvious implementations involve the use  of  ordered  lists  or  binary
  1487. search trees defined by instances of the form:
  1488.  
  1489.     data STree a = Empty | Node a (STree a) (STree a)
  1490.  
  1491.     instance Collects a [a] where ....
  1492.     instance Collects a (STree a) where ....
  1493.  
  1494. Once again, there are significant problems even  with  simple  examples
  1495. using these functions.  As an example, the standard way of  defining  a
  1496. function of type:
  1497.  
  1498.                   Collects a b => [a] -> b
  1499.  
  1500. mapping a list of values to a collection  of  those  values  using  the
  1501. higher order function "foldr":
  1502.  
  1503.     listToCollection = foldr addToCollection emptyCollection
  1504.  
  1505. actually produces a function with ambiguous type:
  1506.  
  1507.     ? :t foldr addToCollection emptyCollection
  1508.     \d139 d140 -> foldr (addToCollection d140) (emptyCollection d139)
  1509.               :: (Collects c b, Collects a b) => [a] -> b
  1510.     ?
  1511.  
  1512. which cannot be resolved, even with an explicit type declaration.
  1513.  
  1514.  
  1515.  
  1516.                                       83
  1517.  
  1518.  
  1519.  
  1520.  
  1521. Introduction to Gofer         14.4.4 Overloading and numeric values             
  1522.  
  1523.  
  1524. 14.4.4 Overloading and numeric values
  1525. -------------------------------------
  1526. One of the most common uses of overloading is to allow the use  of  the
  1527. standard arithmetic operators such as (+), (*) etc. on the elements  of
  1528. a range of numeric types including integers, floating point  values  in
  1529. addition to user defined numeric  types  such  as  arbitrary  precision
  1530. integers,  complex  and  rational  numbers,   vectors   and   matrices,
  1531. polynomials etc.  In Haskell, these features are supported by a  number
  1532. of built-in types and a complex hierarchy of  type  classes  describing
  1533. the operations defined on the elements of each numeric type.
  1534.  
  1535. As an experimental language, intended primarily for  the  investigation
  1536. of general purpose overloading, Gofer has  only  two  built-in  numeric
  1537. types; Int and Float (the second of  which  is  not  supported  in  all
  1538. implementations).  Similarly, although the Gofer system could  be  used
  1539. to implement the  fully  hierarchy  of  Haskell  numeric  classes,  the
  1540. standard prelude uses a single numeric type class Num defined by:
  1541.  
  1542.     class Eq a => Num a where           -- simplified numeric class
  1543.         (+), (-), (*), (/) :: a -> a -> a
  1544.         negate             :: a -> a
  1545.         fromInteger        :: Int -> a
  1546.  
  1547. The first four member functions (+), (-), (*),  (/)  are  the  standard
  1548. arithmetic functions on instances of Num, whilst "negate" denotes unary
  1549. negation.  The final member function, fromInteger is used to coerce any
  1550. integer value to the corresponding value in another  instance  of  Num.
  1551. An expression such as "fromInteger 3" is called an  overloaded  numeric
  1552. constant and has type Num a => a indicating that it can be  used  as  a
  1553. value of any instance of Num.  See below for examples.
  1554.  
  1555. Both Float and Int are defined as  instances  of  Num  using  primitive
  1556. functions for integer and floating point arithmetic:
  1557.  
  1558.     instance Num Int where
  1559.         (+)           = primPlusInt
  1560.         (-)           = primMinusInt
  1561.         (*)           = primMulInt
  1562.         (/)           = primDivInt
  1563.         negate        = primNegInt
  1564.         fromInteger x = x
  1565.  
  1566.     instance Num Float where
  1567.         (+)         = primPlusFloat
  1568.         (-)         = primMinusFloat
  1569.         (*)         = primMulFloat
  1570.         (/)         = primDivFloat 
  1571.         negate      = primNegFloat
  1572.         fromInteger = primIntToFloat
  1573.  
  1574. These definitions make it  possible  to  evaluate  numeric  expressions
  1575. involving both types:
  1576.  
  1577.     ? 2 + 3
  1578.     5
  1579.     (3 reductions, 6 cells)
  1580.  
  1581.  
  1582.                                       84
  1583.  
  1584.  
  1585.  
  1586.  
  1587. Introduction to Gofer         14.4.4 Overloading and numeric values             
  1588.  
  1589.  
  1590.     ? 3.2 + 4.321
  1591.     7.521
  1592.     (3 reductions, 13 cells)
  1593.     ?
  1594.  
  1595. Note  however  that  any  attempt  to  evaluate  an  expression  mixing
  1596. different arithmetic types is likely to cause a type error:
  1597.  
  1598.     ? 4.2 * 4
  1599.     ERROR: Type error in application
  1600.     *** expression     : 4.2 * 4
  1601.     *** term           : 4.2
  1602.     *** type           : Float
  1603.     *** does not match : Int
  1604.     ?
  1605.  
  1606. Further problems occur when we try to define functions intended  to  be
  1607. used with arbitrary instances  of  Num  rather  than  specific  numeric
  1608. types.  As an example of this, the  standard  prelude  function  "sum",
  1609. roughly equivalent to:
  1610.  
  1611.     sum []     = 0
  1612.     sum (x:xs) = x + sum xs
  1613.  
  1614. has type [Int] -> Int,  rather than the  more general Num a => [a] -> a
  1615. which could be used to find the sum of a list of numeric values in  any
  1616. instance of Num.  The problem in this particular case is caused by the
  1617. integer constant 0 in the first line of the definition.  Replacing this
  1618. with the expression fromInteger 0 leads to the following definition for
  1619. a generic sum function of the required type:
  1620.  
  1621.     genericSum       :: Num a => [a] -> a
  1622.     genericSum []     = fromInteger 0
  1623.     genericSum (x:xs) = x + genericSum xs
  1624.  
  1625. For example:
  1626.  
  1627.     ? genericSum [1,2,3]
  1628.     6
  1629.     (10 reductions, 18 cells)
  1630.     ? genericSum [1.0,2.0,3.0]
  1631.     6.0
  1632.     (11 reductions, 27 cells)
  1633.     ?
  1634.  
  1635. The fromInteger function  can  also  be  used  to  solve  the  previous
  1636. problem:
  1637.  
  1638.     ? 4.2 * fromInteger 4
  1639.     16.8
  1640.     (3 reductions, 13 cells)
  1641.     ?
  1642.  
  1643. In Haskell, any integer  constant  k  appearing  in  an  expression  is
  1644. treated as if the programmer had actually written  "fromInteger  k"  so
  1645. that  both  of  the  preceding  problems  are  automatically  resolved.
  1646.  
  1647.  
  1648.                                       85
  1649.  
  1650.  
  1651.  
  1652.  
  1653. Introduction to Gofer         14.4.4 Overloading and numeric values             
  1654.  
  1655.  
  1656. Unfortunately, this  also  creates  some  new  problems;  applying  the
  1657. function fromInteger to each  integer  constant  in  previous  examples
  1658. causes problems with unresolved overloading:
  1659.  
  1660.     ? fromInteger 2 + fromInteger 3
  1661.     ERROR: Unresolved overloading
  1662.     *** type        : Num a => a
  1663.     *** translation : \d143 -> (+) d143 (fromInteger d143 2)
  1664.                                         (fromInteger d143 3)
  1665.     ?
  1666.  
  1667. Once again, Haskell provides a solution to this problem in the form  of
  1668. a `default mechanism' for  numeric  types  which,  once  the  following
  1669. problem has been detected, will typically `default'  the  unknown  type
  1670. represented by the type variable a above to be Int, so that the  result
  1671. is actually equivalent to the following:
  1672.  
  1673.     ? (fromInteger 2 + fromInteger 3) :: Int
  1674.     5
  1675.     (4 reductions, 8 cells)
  1676.     ?
  1677.  
  1678. There are a number of problems with the Haskell default mechanism; both
  1679. theoretical and practical.  In addition, if a default mechanism of some
  1680. form is used then it should also be capable of dealing  with  arbitrary
  1681. user-defined type classes, rather than  a  small  group  of  `standard'
  1682. classes, in order to provide solutions to  the  unresolved  overloading
  1683. problems described in  previous  sections.   Therefore,  for  the  time
  1684. being, Gofer does  not  support  any  form  of  default  mechanism  and
  1685. overloaded numeric constants can only be obtained by  explicit  use  of
  1686. the fromInteger function.
  1687.  
  1688.  
  1689. 14.4.5 Constants in dictionaries
  1690. --------------------------------
  1691. The Gofer system constructs new dictionaries as necessary, and  deletes
  1692. them when they are no longer required.  At any one time,  there  is  at
  1693. most one dictionary for each instance of a class.   Coupled  with  lazy
  1694. evaluation, this has a number of advantages for classes in which member
  1695. functions are defined by variable declarations as in section 9.10.   As
  1696. an example, consider the class Finite defined by:
  1697.  
  1698.     class Finite a  where  members :: [a]
  1699.  
  1700. The only member in this class is a list enumerating the elements of the
  1701. type.  For example:
  1702.  
  1703.     instance Finite Bool  where  members = [False, True]
  1704.  
  1705.     instance (Finite a, Finite b) => Finite (a,b) where
  1706.         members = [ (x,y) | x<-members, y<-members ]
  1707.  
  1708. In order to overcome any problems with unresolved overloading, explicit
  1709. type signatures are often needed to resolve overloading:
  1710.  
  1711.     ? members :: [Bool]
  1712.  
  1713.  
  1714.                                       86
  1715.  
  1716.  
  1717.  
  1718.  
  1719. Introduction to Gofer         14.4.5 Constants in dictionaries                  
  1720.  
  1721.  
  1722.     [False, True]
  1723.     (6 reductions, 26 cells)
  1724.     ? length (members :: [((Bool,Bool),(Bool,Bool))])
  1725.     16
  1726.     (103 reductions, 195 cells)
  1727.     ?
  1728.  
  1729. In some cases, the required overloading is implicit  from  the  context
  1730. and no additional type information is required,  as  in  the  following
  1731. example:
  1732.  
  1733.     ? [ x && y | (x,y) <- members ]
  1734.     [False, False, False, True]
  1735.     (29 reductions, 90 cells)
  1736.     ?
  1737.  
  1738. We can also use the technique of passing a `dummy' parameter to resolve
  1739. overloading problems in a function definition:
  1740.  
  1741.     size  :: Finite a => a -> Int
  1742.     size x = length (members `asTypeOf` [x])
  1743.  
  1744. which calculates the number of elements of  a  finite  type,  given  an
  1745. arbitrary element of that type:
  1746.  
  1747.     ? size (True,False)
  1748.     4
  1749.     (31 reductions, 60 cells)
  1750.     ?
  1751.  
  1752. Now consider the expression "size (True,False)  +  size  (True,False)".
  1753. At first glance, we expect  this  to  repeat  the  calculation  in  the
  1754. previous example two  times,  requiring  approximately  twice  as  many
  1755. reductions and cells as before.  However,  before  this  expression  is
  1756. evaluated, Gofer constructs a dictionary for Finite  (Bool,Bool).   The
  1757. evaluation of the first summand forces Gofer to evaluate the value  for
  1758. "members" in this dictionary.  Since precisely the same  dictionary  is
  1759. used to calculate the value of the second summand,  the  evaluation  of
  1760. "members" is not repeated and the complete  calculation  actually  uses
  1761. rather fewer reductions and cells:
  1762.  
  1763.     ? size (True,False) + size (True,False)
  1764.     8
  1765.     (51 reductions, 90 cells)
  1766.     ?
  1767.  
  1768. On the other hand, repeating the original calculation gives exactly the
  1769. same number of reductions and cells as before, because the dictionaries
  1770. constructed at the beginning of each calculation are not  retained  for
  1771. use in subsequent calculations.
  1772.  
  1773. We can force Gofer to construct specific  dictionaries  whilst  reading
  1774. from a file of definitions, so that they are not deleted at the end  of
  1775. each calculation, using an explicitly typed  variable  definition  such
  1776. as:
  1777.  
  1778.  
  1779.  
  1780.                                       87
  1781.  
  1782.  
  1783.  
  1784.  
  1785. Introduction to Gofer         14.4.5 Constants in dictionaries                  
  1786.  
  1787.  
  1788.     boolBoolMembers = members :: [(Bool,Bool)]
  1789.  
  1790. This forces Gofer to construct the dictionary Finite (Bool,Bool)  when
  1791. the file of definitions is loaded and prevents it from being deleted at
  1792. the end of each calculation.  Having  loaded  a  file  containing  this
  1793. definition, the  first two  attempts  to  evaluate  "size (True,False)"
  1794. give:
  1795.  
  1796.     ? size (True,False)
  1797.     4
  1798.     (31 reductions, 60 cells)
  1799.     ? size (True,False)
  1800.     4
  1801.     (20 reductions, 32 cells)
  1802.     ?
  1803.  
  1804.  
  1805. 14.4.6 The monomorphism restriction
  1806. -----------------------------------
  1807. This section  describes  a  technique  used  to  limit  the  amount  of
  1808. overloading used in the definition of certain values to avoid a  number
  1809. of technical problems.  This particular topic has attracted quite a lot
  1810. of attention within the Haskell community where  it  is  affectionately
  1811. known as the `dreaded monomorphism restriction'.  Although the  initial
  1812. formulation of the rule was rather cumbersome and limiting, the current
  1813. version used in both  Gofer  and  Haskell  is  unlikely  to  cause  any
  1814. problems in practice.  In  addition,  many  of  the  examples  used  to
  1815. motivate the need for the monomorphism restriction in Haskell occur  as
  1816. a result  of  the  use  of  implicitly  overloaded  numeric  constants,
  1817. described in section 14.4.4, and hence do not occur in Gofer.
  1818.  
  1819. The monomorphism restriction takes its name from the way  in  which  it
  1820. limits the amount of polymorphism that can be used in particular  kinds
  1821. of declaration.  Although we touch  on  this  point  in  the  following
  1822. discussion, the description given here uses  an  equivalent,  but  less
  1823. abstract approach, based on observations about  the  implementation  of
  1824. overloaded functions.
  1825.  
  1826. Basic ideas:
  1827. ------------
  1828. As we have seen,  the  implementation  of  overloading  used  by  Gofer
  1829. depends on being able to add extra arguments to a  function  definition
  1830. to supply the required dictionary parameters.   For  example,  given  a
  1831. function definition such as:
  1832.  
  1833.     isElement x []     =  False
  1834.     isElement x (y:ys) =  x==y || isElement x ys
  1835.  
  1836. we first add a dictionary parameter for the use of the overloaded  (==)
  1837. operator on the right hand side, obtaining:
  1838.  
  1839.     isElement x []     = False
  1840.     isElement x (y:ys) = (==) d x y || isElement x ys
  1841.  
  1842. Finally, we have to add the variable d  as  a  new  parameter  for  the
  1843. function isElement, on both the  left  and  right  hand  sides  of  the
  1844.  
  1845.  
  1846.                                       88
  1847.  
  1848.  
  1849.  
  1850.  
  1851. Introduction to Gofer         14.4.6 The monomorphism restriction               
  1852.  
  1853.  
  1854. definition:
  1855.  
  1856.     isElement d x []     = False
  1857.     isElement d x (y:ys) = (==) d x y || isElement d x ys
  1858.  
  1859. The monomorphism restriction imposes conditions which prevent this last
  1860. step from being used for certain kinds  of  value  binding.
  1861.  
  1862. Declaration groups:
  1863. -------------------
  1864. Before giving the full details, it  is  worth  pointing  out  that,  in
  1865. general,  the  monomorphism  restriction  affects   groups   of   value
  1866. declarations rather than just individual  definitions.   To  illustrate
  1867. this point, consider the function definitions:
  1868.  
  1869.     f x y  =  x==y || g x y
  1870.     g x y  =  not (f x y)
  1871.  
  1872. Adding an appropriate dictionary parameter for the (==) operator gives:
  1873.  
  1874.     f x y  =  (==) d x y || g x y
  1875.     g x y  =  not (f x y)
  1876.  
  1877. The next stage is to  make  this  dictionary  variable  into  an  extra
  1878. parameter to the function f wherever it appears, giving:
  1879.  
  1880.     f d x y  =  (==) d x y || g x y
  1881.     g x y    =  not (f d x y)
  1882.  
  1883. But now the right hand side  of  the  second  definition  mentions  the
  1884. dictionary variable d  which  must  therefore  be  added  as  an  extra
  1885. parameter to g:
  1886.  
  1887.     f d x y  =  (==) d x y || g d x y
  1888.     g d x y  =  not (f d x y)
  1889.  
  1890. In other words, if dictionary parameters are added  to  any  particular
  1891. function  definition,  then  each  use  of  that  function  in  another
  1892. definition will also be require  extra  dictionary  parameters.   As  a
  1893. result, the monomorphism restriction has to be applied to the  smallest
  1894. groups of  declarations  such  that  any  pair  of  mutually  recursive
  1895. bindings are in the same group.
  1896.  
  1897. As the example above shows, if one (or more) of the bindings in a given
  1898. declaration group is affected by the monomorphism restriction  so  that
  1899. the appropriate dictionary parameters cannot be added as parameters for
  1900. that definition, then the same condition must also be imposed on all of
  1901. the other bindings in the group.  [Adding the extra parameter to  f  in
  1902. the example forces us to  add  an  extra  parameter  for  g;  if  extra
  1903. parameters were not permitted for g then they could not be added to f.]
  1904.  
  1905.  
  1906.  
  1907.  
  1908.  
  1909.  
  1910.  
  1911.  
  1912.                                       89
  1913.  
  1914.  
  1915.  
  1916.  
  1917. Introduction to Gofer         14.4.6 The monomorphism restriction               
  1918.  
  1919.  
  1920. Restricted bindings:
  1921. --------------------
  1922. There are three main reasons for avoiding adding dictionary  parameters
  1923. to a particular value binding:
  1924.  
  1925.   o  Dictionary parameters unnecessary.  If the dictionary  values  are
  1926.      completely determined by context then it is not necessary to  pass
  1927.      the appropriate values as dictionary parameters.  For example, the
  1928.      function definition:
  1929.  
  1930.          f x  =   x == 0  ||  x == 2
  1931.  
  1932.      can be translated as:
  1933.  
  1934.          f x  =   (==) {dict} x 0  ||  (==) {dict} x 2
  1935.  
  1936.      where, in both cases, the symbol {dict} denotes the dictionary for
  1937.      Eq Int.  As a further optimisation, once the dictionary  is  fully
  1938.      determined, this can be simplified to:
  1939.  
  1940.          f x  =   primEqInt x 0 || primEqInt x 2
  1941.  
  1942.   o  Dictionary parameters cannot be added in a pattern  binding.   One
  1943.      potential solution to this problem would be to replace the pattern
  1944.      binding by an equivalent set of function bindings.   In  practice,
  1945.      we do not use this technique because it typically causes ambiguity
  1946.      problems, as illustrated by the pattern binding:
  1947.  
  1948.          (plus,times) = ((+), (*))
  1949.  
  1950.      Translating this into a group of function bindings gives:
  1951.  
  1952.          newVariable  = ((+), (*))
  1953.          plus         = fst newVariable     -- fst (x,_) = x
  1954.          times        = snd newVariable     -- snd (_,y) = y
  1955.  
  1956.      The type of newVariable is (Num a, Num b) => (a->a->a, b->b->b) so
  1957.      that  the  correct  translation  of  these  bindings   using   two
  1958.      dictionary variables gives:
  1959.  
  1960.          newVariable da db = ((+) da, (*) db)
  1961.          plus da db        = fst (newVariable da db)
  1962.          times da db       = snd (newVariable da db)
  1963.  
  1964.      and hence the correct types for plus and times are:
  1965.  
  1966.          plus  :: (Num a, Num b) => a -> a -> a
  1967.          times :: (Num a, Num b) => b -> b -> b
  1968.      
  1969.      both of which are ambiguous.
  1970.  
  1971.   o  Adding dictionary parameters may translate a  variable  definition
  1972.      into  a  function  definition,  loosing  the  benefits  of  shared
  1973.      evaluation.  As an  example,  consider  the  following  definition
  1974.      using the function "size" and the class Finite  described  in  the
  1975.      previous section:
  1976.  
  1977.  
  1978.                                       90
  1979.  
  1980.  
  1981.  
  1982.  
  1983. Introduction to Gofer         14.4.6 The monomorphism restriction               
  1984.  
  1985.  
  1986.          twiceSize x = n + n  where n = size x
  1987.  
  1988.      Since the variable n is defined using a local definition, we would
  1989.      not expect to have to evaluate size x more than once to  determine
  1990.      the  value  of  twiceSize.   However,  adding   extra   dictionary
  1991.      parameters without restriction gives:
  1992.  
  1993.          twiceSize d x  = n d + n d  where  n d = size d x
  1994.  
  1995.      Now that n has been replaced by a function, the evaluation will be
  1996.      repeated, once for each occurrence of the expression  "n  d".   In
  1997.      order to avoid this kind of problem, the monomorphism  restriction
  1998.      does not usually allow extra parameters to be added to a  variable
  1999.      definition.  Thus the original definition above will be translated
  2000.      to give:
  2001.  
  2002.          twiceSize d x  =  n + n  where n = size d x
  2003.  
  2004.      Note that the same rule is applied to variable definitions at  the
  2005.      top-level of a file of definitions, resulting in an error  if  any
  2006.      dictionary parameters are required for the right hand side of  the
  2007.      definition.  As an example of this:
  2008.  
  2009.          twiceMembers = members ++ members
  2010.  
  2011.      which produces an error message of the form:
  2012.  
  2013.          ERROR "ex" (line 157): Unresolved top-level overloading
  2014.          *** Binding             : twiceMembers
  2015.          *** Inferred type       : [_7]
  2016.          *** Outstanding context : Finite _7
  2017.          ?
  2018.  
  2019.      [COMMENT: A type expression of the form _n (such  as  _7  in  this
  2020.      particular example) represents a  fixed  (i.e.  monomorphic)  type
  2021.      variable.]
  2022.  
  2023.      In  the  case  of  a  variable   declaration,   the   monomorphism
  2024.      restriction can be overcome by giving an explicit  type  signature
  2025.      including an appropriate context, to indicate  that  the  variable
  2026.      defined is intended to be used as an overloaded  value.   In  this
  2027.      case, we need only include the declaration:
  2028.  
  2029.          twiceMembers :: Finite a => [a]
  2030.  
  2031.      in the file containing the definition for twiceMembers to suppress
  2032.      the previous error message and allow the function to be used as  a
  2033.      fully overloaded variable.
  2034.  
  2035.      Note that the monomorphism restriction interferes with the use  of
  2036.      polymorphism.  For example, the definition:
  2037.  
  2038.          aNumber = length (twiceMembers::[Bool]) +
  2039.                    length (twiceMembers::[(Bool,Bool)])
  2040.                    where twiceMembers = members ++ members
  2041.  
  2042.  
  2043.  
  2044.                                       91
  2045.  
  2046.  
  2047.  
  2048.  
  2049. Introduction to Gofer         14.4.6 The monomorphism restriction               
  2050.  
  2051.  
  2052.      will not be accepted because the monomorphism  restriction  forces
  2053.      the local definition of  "twiceMembers"  to  be  restricted  to  a
  2054.      single overloading (the dictionary parameter supplied to each  use
  2055.      of members must be constant throughout the local definition):
  2056.  
  2057.          ERROR "ex" (line 12): Type error in type signature expression
  2058.          *** term           : twiceMembers
  2059.          *** type           : [(Bool,Bool)]
  2060.          *** does not match : [Bool]
  2061.          ?
  2062.  
  2063.      Once again, this problem can  be  fixed  using  an  explicit  type
  2064.      declaration:
  2065.  
  2066.          aNumber = length (twiceMembers::[Bool]) +
  2067.                    length (twiceMembers::[(Bool,Bool)])  
  2068.                    where twiceMembers :: Finite a => [a]
  2069.                          twiceMembers  = members ++ members
  2070.  
  2071.  
  2072. Formal definition:
  2073. ------------------
  2074. The  examples  above  describe  the  motivation  for  the  monomorphism
  2075. restriction, captured by the following definition:
  2076.  
  2077. Dictionary variables will not  be  used  as  extra  parameters  in  the
  2078. definition of a value in a given declaration group G if:
  2079.  
  2080.    either:  G includes a pattern binding
  2081.  
  2082.        or:  G includes a variable declaration, but does not include  an
  2083.             explicit type signature for any of  the  variables  in  the
  2084.             group.
  2085.  
  2086. If neither of these conditions hold, then equivalent sets of dictionary
  2087. parameters will be added to each declaration in the group.
  2088.  
  2089.  
  2090.  
  2091.  
  2092.  
  2093.  
  2094.  
  2095.  
  2096.  
  2097.  
  2098.  
  2099.  
  2100.  
  2101.  
  2102.  
  2103.  
  2104.  
  2105.  
  2106.  
  2107.  
  2108.  
  2109.  
  2110.                                       92
  2111.  
  2112.  
  2113.